package com.shamine.kuaiqiao.blink.receiver

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.shamine.kuaiqiao.blink.gallery.GalleryActivity
import java.util.*

/**
 * 重启后重新设置提醒
 * Created by Caine on 2017/12/22.
 */
class BlinkBootCompleteReceiver: BroadcastReceiver() {
    override fun onReceive(p0: Context?, p1: Intent?) {
        if (p1?.action == Intent.ACTION_BOOT_COMPLETED ) setAlarm(p0!!)
    }

    private fun setAlarm(context: Context) {
        val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        //间隔时间 12 hours
        val interval = 1000L*60*60*12
        val calendar = Calendar.getInstance()
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val day = calendar.get(Calendar.DATE)
        val month = calendar.get(Calendar.MONTH)
        val year = calendar.get(Calendar.YEAR)
        //设置到第二天
        if (hour >= 18){
            when(month){
                1,3,5,7,8,10,12 -> {
                    if (day == 31) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
                4,6,9,11 -> {
                    if (day == 30) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
                2 -> {
                    if (year % 4 == 0 && day == 29){
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    } else if ( day == 28) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
            }
        }
        //设置到下午
        if (hour in 6 until 18) calendar.set(Calendar.HOUR_OF_DAY,18)
        if (hour in 0 until 6) calendar.set(Calendar.HOUR_OF_DAY,6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND,0)
        val intent = Intent(context, BlinkReceiver::class.java)
        intent.action = GalleryActivity.ACTION
        val pIntent = PendingIntent.getBroadcast(context,1228,intent,0)
        manager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,interval,pIntent)
    }
}